package com.watson.http;

import android.app.Dialog;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.watson.R;
import com.watson.utils.LogUtils;
import com.watson.utils.ToastUtil;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;

public abstract class HttpCallbackWdss extends AbsCallback<JsonBeanWdss> {
    private Dialog mLoadingDialog;

    @Override
    public JsonBeanWdss convertResponse(okhttp3.Response response) throws Throwable {
        return JSON.parseObject(response.body().string(), JsonBeanWdss.class);
    }

    @Override
    public void onSuccess(Response<JsonBeanWdss> response) {
        LogUtils.e("TAG", response.body() + "");
        JsonBeanWdss bean = response.body();
        if (bean != null) {
            if (bean.isIsSuccess()) {
                onSuccess(bean.isIsSuccess(), bean.getMessage(), bean.getData());
            } else {
                ToastUtil.show(bean.getMessage());
            }
        } else {
            LogUtils.e("服务器返回值异常--->bean = null");
        }
    }

    @Override
    public void onError(Response<JsonBeanWdss> response) {
        LogUtils.e(response.body() + "");
        Throwable t = response.getException();
        LogUtils.e("网络请求错误---->" + t.getClass() + " : " + t.getMessage());
        if (t instanceof SocketTimeoutException || t instanceof ConnectException || t instanceof UnknownHostException || t instanceof UnknownServiceException || t instanceof SocketException) {
            ToastUtil.show(R.string.load_failure);
        }
        if (showLoadingDialog() && mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
        onError();
    }

    public void onError() {

    }


    public abstract void onSuccess(boolean code, String msg, Object info);

    @Override
    public void onStart(Request<JsonBeanWdss, ? extends Request> request) {
        onStart();
    }

    public void onStart() {
        if (showLoadingDialog()) {
            if (mLoadingDialog == null) {
                mLoadingDialog = createLoadingDialog();
            }
            mLoadingDialog.show();
        }
    }

    @Override
    public void onFinish() {
        if (showLoadingDialog() && mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    public Dialog createLoadingDialog() {
        return null;
    }

    public boolean showLoadingDialog() {
        return false;
    }

}
